    <template>

        <div class="dashboard-container">
            <div id="container">
                <el-form :inline="true" style="margin-left: 15px;">
                    <el-form-item><el-input v-model="tableData.goods" placeholder="请输入商品"  style="width: 200px"></el-input></el-form-item>
                    <!-- <el-form-item >
                    <el-select v-model="form.storehouse" class="size"  placeholder="请选择仓库" prop="storehouse"  style="width: 200px"> 
                    <el-option 
                    v-for="wh in storehouses" 
                    :key="wh.id" 
                    :label="wh.storehouse" 
                    :value="wh.storehouse">
                    
                    </el-option>
                </el-select>
                </el-form-item> -->
                    <el-form-item> 
                        <el-select v-model="tableData.category" class="size" placeholder="请选择分类" prop="category"  style="width: 200px">
                    <el-option 
                    v-for="wh in categories" 
                    :key="wh.id" 
                    :label="wh.category" 
                    :value="wh.category">
                    </el-option>
                </el-select>
                </el-form-item>
                    <el-button type="primary" @click="pageQuery()" icon="el-icon-search"
                        v-loading.fullscreen.lock="fullscreenLoading">查询</el-button>
                    <el-button type="primary" icon="el-icon-close" @click="reset()">重置</el-button>
                    <el-button type="primary" icon="el-icon-plus el-icon-plus" @click="dialogFormVisible2=true">添加</el-button>
                </el-form>
            </div>

            <el-table :data="tableData" border style="width: 100%; margin-left: 15px;" align="center">
                <el-table-column prop="id" label="ID" width="50">
                </el-table-column>
                <el-table-column prop="goods" label="商品" width="150" align="center" type="primary">

                </el-table-column>
                <el-table-column prop="storehouse" label="仓库" width="150" align="center">
                </el-table-column>
                <el-table-column prop="category" label="分类名称" width="150" align="center">
                </el-table-column>
                <el-table-column prop="quantity" label="数量" width="150" align="center">
                </el-table-column>
                <el-table-column prop="remark" label="备注" align="center">
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                    

                        <el-button type="primary" size="small" @click="handleStockAction(scope.row, '入库')"
                            icon="el-icon-circle-plus-outline">入库</el-button>

                        <el-button type="primary" size="small" @click="handleStockAction(scope.row, '出库')"
                            icon="el-icon-remove-outline">出库</el-button>

                        <el-button type="primary" size="small" @click="del(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination align="center" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="page" :background="background" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
            </el-pagination>


            <el-dialog title="物品添加" :visible.sync="dialogFormVisible2">
            <el-form :model="form" :rules="rules2" ref="addForm"> 
                <el-form-item label="物品名" :label-width="formLabelWidth" prop="goods">  
                <el-input v-model="form.goods" class="size"></el-input>
                
                <label style="margin-left: 90px;">仓库:</label>
                <el-select v-model="form.storehouse" class="size" placeholder="请选择仓库" prop="storehouse"> 
                    <el-option 
                    v-for="wh in storehouses" 
                    :key="wh.id" 
                    :label="wh.storehouse" 
                    :value="wh.storehouse">
                    </el-option>
                </el-select>
                </el-form-item>

                <el-form-item label="分类" :label-width="formLabelWidth" prop="category"> 
                <el-select v-model="form.category" class="size" placeholder="请选择分类" prop="category">
                    <el-option 
                    v-for="wh in categories" 
                    :key="wh.id" 
                    :label="wh.category" 
                    :value="wh.category">
                    </el-option>
                </el-select>
                <label style="margin-left: 90px;">备注：</label>
                <el-input v-model="form.remark" class="size" prop="remark"></el-input>  
                </el-form-item>

                <el-form-item label="数量" :label-width="formLabelWidth" prop="quantity">  
                <el-input v-model.number="form.quantity" class="size"></el-input>  
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>  
            </div>
            </el-dialog>

            <!-- Form -->
            <el-dialog title="出库" :visible.sync="dialogFormVisible"  highlight-current-row @current-change="handleCurrentChange">
                <el-dialog title="用户选择" :visible.sync="innerVisible" append-to-body class="UserSize" highlight-current-row @current-change="handleCurrentChange">
                    <el-table :data="usertable" border align="center">
                        <el-table-column prop="id" label="ID">
                        </el-table-column>
                        <el-table-column prop="account" label="账号" align="center" type="primary" @click="b()">
                        </el-table-column>
                        <el-table-column prop="name" label="名称 " width="150" align="center">
                        </el-table-column>
                        <el-table-column prop="age" label="年龄" width="150" align="center">
                        </el-table-column>
                        <el-table-column prop="gender" label="性别" width="50" align="center">
                        </el-table-column>
                        <el-table-column prop="role" label="角色" align="center" >
                        </el-table-column>
                        <el-table-column prop="number" label="电话" align="center" width="150">
                        </el-table-column>
                        <el-table-column align="center" label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="small" @click="sel2(scope.row.id),innerVisible=false"
                                    icon=" el-icon-edit">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-dialog>

                <el-form :model="form" :rules="rules" ref="stockForm" style="width: 50%;" >
                    <el-form-item label="商品名称" :label-width="formLabelWidth">
                        <el-input v-model="form.goods" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="管理员" :label-width="formLabelWidth">
                        <el-input v-model="user.account" @click.native="innerVisible = true">选择</el-input>
                    </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
                    <el-select v-model="form.status" placeholder="请选择">
                        <el-option label="出库" value="出库"></el-option>
                    </el-select>                    
                </el-form-item>
        <el-form-item label="数量" :label-width="formLabelWidth">
            <el-input-number v-model="form.quantity" autocomplete="off" 
            :min="1" :max="form.originalQuantity" @change="handleQuantityChange"></el-input-number>组
            
        </el-form-item>
                  
                    <el-form-item label="备注" :label-width="formLabelWidth">
                        <el-input autocomplete="off" type="textarea" :rows="2" placeholder="请输入内容"
                            v-model="form.remark" disabled></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="update(),dialogFormVisible=false">确 定</el-button>
                    <div slot="footer" class="dialog-footer">
                        
                    </div>
                </div>
            </el-dialog>

            
            <!-- Form -->
            <el-dialog title="入库" :visible.sync="dialogFormVisible3" highlight-current-row @current-change="handleCurrentChange" >
                <el-dialog title="用户选择" :visible.sync="innerVisible2" append-to-body class="UserSize" highlight-current-row @current-change="handleCurrentChange">
                    <el-table :data="usertable" border align="center">
                        <el-table-column prop="id" label="ID">
                        </el-table-column>
                        <el-table-column prop="goods" label="商品" align="center" type="primary" >
                        </el-table-column>
                        <el-table-column prop="storehouse" label="仓库" width="150" align="center">
                        </el-table-column>
                        <el-table-column prop="category" label="分类名称" width="150" align="center">
                        </el-table-column>
                        <el-table-column prop="quantity" label="数量" width="150" align="center">
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" align="center">
                        </el-table-column>
                        <el-table-column align="center" label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="small" @click="updById(scope.row.id)"
                                    icon=" el-icon-edit">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-dialog>
                <el-form :model="form" :rules="rules" ref="stockForm" style="width: 50%;">
                    <el-form-item label="商品名称" :label-width="formLabelWidth">
                        <el-input v-model="form.goods" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="管理员" :label-width="formLabelWidth">
                        <el-input v-model="user.name" @click.native="innerVisible = true">选择</el-input>
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth"  prop="status">
                            <el-select v-model="form.status" placeholder="请选择">
                            <el-option label="入库" value="入库"></el-option>
                        </el-select>                    
                        </el-form-item>
                    
                      <el-form-item label="数量" :label-width="formLabelWidth">
            <el-input-number v-model="form.quantity" autocomplete="off" 
            :min="1" :max="form.originalQuantity" @change="handleQuantityChange"></el-input-number>组
            
        </el-form-item>

                    <el-form-item label="备注" :label-width="formLabelWidth">
                        <el-input autocomplete="off" type="textarea" :rows="3" placeholder="请输入内容"
                            v-model="form.remark" disabled></el-input>
                    </el-form-item>

                    
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible3 = false">取 消</el-button>
                    <el-button type="primary" @click="update()">确 定</el-button>
                
                </div>
            </el-dialog>
        </div>

    </template>

    <script>
    import { page, sel, getById,upd,addGoods} from '@/api/Goods';
    import {adminpage,selectById} from '@/api/AdminManafe';
    import {sele} from '@/api/Storage';
    import {getByCategory} from '@/api/GoodsCategory';
    export default {
        data() {
            // 添加表单验证规则
            const validateStatus = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请选择状态'));
                } else {
                    callback();
                }
            };
            
            return {
                rules: {
                    status: [
                        { validator: validateStatus, trigger: 'change' },

                    ],
                    
                },


                 rules2: {
                    goods: [
                    { required: true, message: '商品名称不能为空', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
                    ],
                    category: [
                    { required: true, message: '请选择分类', trigger: 'change' }
                    ],
                    storehouse: [
                    { required: true, message: '请选择仓库', trigger: 'change' }
                    ],
                    quantity: [
                    { required: true, message: '数量不能为空', trigger: 'blur' },
                   
                    ],
                    remark: [
                    { required: true, message: '备注不能为空', trigger: 'blur' },
                    { max: 200, message: '不能超过200个字符', trigger: 'blur' }
                    ]
                },
                
                categories: [], // 用于存储分类数据
                storehouses: [], // 用于存储仓库数据
                originalQuantity: 0,
                page: 1,
                pageSize: 10,
                tableData: [],
                usertable: [],
                total: 0,
                dialogTableVisible: false,
                dialogFormVisible: false,
                dialogFormVisible2:false,
                dialogFormVisible3:false,
                formLabelWidth: '120px',
                outerVisible: false,
                innerVisible: false,
                textatea: '',
                form: { 
                    id:'',
                    goods:'',
                    storehouse:'',
                    category:'',
                    quantity:1,
                    account:'',
                    role:'',
                    remark:'',
                    status:"",
                },
                form3:{
                    id:'',
                    goods:'',
                    storehouse:'',
                    category:'',
                    quantity:'',
                    remark:'',
                },
                
                user:{
                    account:'',
                    role:'',
                },
                
            }
        },

        //服务启动后自动执行分页查询
        created() {
            this.pageQuery();
            this.UserPageQuery();
            this.loadStorehouses();
            this.loadCategories();
        },

        methods: {
            
            //分页查询
            pageQuery() {
            const params = {
                goods: this.tableData.goods || null,
                category: this.tableData.category || null,
                storehouse: this.tableData.storehouse || null,
                page: this.page,
                pageSize: this.pageSize
            }
            page(params).then(res => {
                this.total = res.data.data.total
                this.tableData = res.data.data.records
            })
        },
            
            // 添加提交表单方法
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.update();
                    } else {
                        this.$message.error('请填写完整信息');
                        return false;
                    }
                });
            },
            //内表用户分页查询
            UserPageQuery() {
                const params2 = {
                    id:null,
                    account:null,
                    name:null,
                    age:null,
                    gender:null,
                    role:null,
                    number:null,
                    page:this.page,
                    pageSize:this.pageSize
                }
                adminpage(params2).then(res => {
                    this.total = res.data.data.total
                    this.usertable = res.data.data.records
                })
            },
            //重置
           reset() {
            this.tableData.goods = ''
            this.tableData.category = ''
            this.tableData.storehouse = ''
            this.pageQuery() // 重置后重新查询
            },

            // 添加提交表单方法
            submitAddForm() {
            this.$refs.addForm.validate((valid) => {
            if (valid) {
                addGoods(this.form).then(res => {
                this.$message.success("添加成功");
                this.pageQuery();
                this.dialogFormVisible2 = false;
                this.$refs.addForm.resetFields(); // 重置表单
                }).catch(error => {
                this.$message.error("添加失败: " + error.message);
                });
            } else {
                this.$message.error('请填写完整且正确的表单信息');
                return false;
            }
            });
            },
            
            //删除
            del(id) {
                this.$confirm(`此操作将永久删除ID=${id}的数据, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    getById(id)
                        .then(res => {
                            if (res.data.code === 1) {
                                this.$message({
                                    type: 'error',
                                    message: '删除失败!'
                                })
                            } else {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                })
                                this.pageQuery()
                            }
                        })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },

            //修改
            updById(id) {
                this.$router.push({
                    path: '/goods/AddAndUpdate',
                    query: { id: id }
                })
            },

            //修改
            update() {
            if (!this.form.status) {
                this.$message.error("请选择状态");
                return;
            }
            
            // 获取用户输入的修改量
            const changeQuantity = this.form.quantity;
            
            // 如果是出库操作，验证数量是否足够
            if (this.form.status === '出库' && changeQuantity > this.originalQuantity) {
                this.$message.error("出库数量不能超过库存数量");
                return;
            }
            
            this.form.account = this.user.account;
            this.form.role = this.user.role;
            
            // 确保传递的是修改量，后端会处理计算
            upd(this.form).then(res => {
                this.$message.success("操作成功");
                this.dialogFormVisible = false;
                this.dialogFormVisible3 = false;
                this.pageQuery();
                this.user.account = "";
            });
            },
            //查询
            sel(id) {
                sel(id).then(res => {
            const data = res.data.data;
            // 只更新需要的字段，保留quantity=1
            this.form.id = data.id;
            this.form.goods = data.goods;
            this.form.storehouse = data.storehouse;
            this.form.category = data.category;
            this.form.remark = data.remark;
            // 保存原始库存数量用于验证
            this.originalQuantity = data.quantity;
            });
            },

            sel2(id){
                selectById(id).then(res=>{
                    this.user= res.data.data;
                    
                })
            },
            
            async handleStockAction(row, actionType) {
    try {
        await this.sel(row.id); // 等待数据加载完成
        this.$set(this.form, 'status', ''); // 先清空状态
        this.originalQuantity = row.quantity; // 保存原始库存数量
        
        if (actionType === '入库') {
            this.dialogFormVisible3 = true;
        } else if (actionType === '出库') {
            this.dialogFormVisible = true;
        }
    } catch (error) {
        console.error("操作失败:", error);
        this.$message.error("操作失败");
    }
    },

    loadStorehouses() {
           sele().then(response => {
                    if (response.data.code === 200) {
                        this.storehouses = response.data.data; // 保存仓库数据
                    } else {
                        this.$message.error('加载仓库失败');
                    }
                })
                .catch(error => {
                    console.error(error);
                    this.$message.error('服务端错误');
                });
        },

        loadCategories() {
            getByCategory().then(response => {
                    if (response.data.code === 200) {
                        this.categories = response.data.data; // 保存分类数据
                    } else {
                        this.$message.error('加载分类失败');
                    }
                })
                .catch(error => {
                    console.error(error);
                    this.$message.error('服务端错误');
                });
    },
   
            handleSizeChange(val) {
                this.pageSize = val
                this.pageQuery()
            },
            handleCurrentChange(val) {
                this.page = val
                this.pageQuery()
            },
            // 监控多选框事件
            handleSelectionChange(selection) {
                this.selectNum = selection.length;
                this.selection = selection;
            },
        
        },
        submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 添加数量验证方法
        validateQuantity(rule, value, callback) {
            if (value <= 0) {
            callback(new Error('数量必须大于0'));
            } else if (!Number.isInteger(value)) {
            callback(new Error('必须是整数'));
            } else {
            callback();
            }
        }
    }


    </script>

    <style scoped>
    .size {
        height: 100%;
        width: 35%;
    }

    .UserSize {
        height: 700px;
        width: 1900px;
    }
    </style>